<?php
///
namespace lxsphp\Core;

///
use lxsphp\Load;

/**
 * 核心 - [配置管理]类
 *
 * @version $Id: Config.php 192 2014-07-18 02:27:45Z linsir123 $
 * @package lxsphp\Core
 */
class Config
{
	/**
	 * 配置数据
	 *
	 * @var array
	 */
	public $data = array();

	/**
	 * 默认包名
	 */
	const PCK_DEFAULT = 'LXSPHP';

	/**
	 * 构造函数
	 */
	public function __construct()
	{
		foreach (array('app', 'store') as $name) {
			$file = $this->_getFile($name);

			///
			$data = Load::file($file);
			$custom = Load::file($file, APP_DIR, false);
			if (! empty($custom) && is_array($custom))
				$data = $this->mergeArrays($data, $custom);

			///
			$this->data[self::PCK_DEFAULT][$name] = $data;
		}
	}

	/**
	 * 获取配置信息
	 * // 键为字符串并以'.'分隔，第一部份为配置文件
	 *
	 * @param string $key 选项的键值
	 * @param string $package 包名
	 *
	 * @return mixed
	 */
	public function get($key, $package = null)
	{
		if (empty($key))
			return null;

		///
		if (empty($package))
			$package = self::PCK_DEFAULT;

		///
		$keys = explode('.', $key);
		$name = array_shift($keys);
		if (! isset($this->data[$package][$name])) {
			$file = $this->_getFile($name, $package);
			$this->data[$package][$name] = Load::file($file, APP_DIR);
		}

		///
		$exists = true;
		$conf = $this->data[$package][$name];
		foreach ($keys as $k) {
			if (is_array($conf) && isset($conf[$k]))
				$conf = $conf[$k];
			else {
				$exists = false;
				break;
			}
		}

		///
		return $exists ? $conf : null;
	}

	/**
	 * 数组递归合并
	 *
	 * @param array $arr1
	 * @param array $arr2
	 *
	 * @return array
	 */
	public function mergeArrays($arr1, $arr2)
	{
		foreach ($arr2 as $k => $val) {
			if (is_array($arr1) && is_array($val) && array_key_exists($k, $arr1))
				$arr1[$k] = $this->mergeArrays($arr1[$k], $arr2[$k]);
			else
				$arr1[$k] = $val;
		}

		return $arr1;
	}

	/**
	 * 取得配置文件的加载路径
	 *
	 * @param string $name 文件名称
	 * @param string $package 包名
	 *
	 * @return string
	 */
	private function _getFile($name, $package = self::PCK_DEFAULT)
	{
		if ($package == self::PCK_DEFAULT || empty($package))
			$file = sprintf("Config/%s.php", $name);
		else
			$file = sprintf("Config/%s/%s.php", $package, $name);

		///
		return $file;
	}
}
